package com.dony.statistic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dony.statistic.domain.OrderDailySale;
import com.dony.statistic.domain.OrderMonthSale;
import com.dony.statistic.mapper.OrderMonthSaleMapper;
import com.dony.statistic.service.IOrderDailySaleService;
import com.dony.statistic.service.IOrderMonthSaleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;

/**
 * 订单Service业务层处理
 *
 * @author dony
 * @date 2022-09-07
 */
@Slf4j
@Service("OrderMonthSaleService")
public class OrderMonthSaleServiceImpl extends ServiceImpl<OrderMonthSaleMapper, OrderMonthSale> implements IOrderMonthSaleService {

    @Resource
    IOrderDailySaleService dailySaleService;

    /**
     * 同步月度数据
     */
    @Override
    public void syncMonthOrderData(Long deptId) {
        LocalDate now = LocalDate.now();
        for (int i = 0; i < 12; i++) {
            QueryWrapper<OrderMonthSale> orderMonthSaleQueryWrapper = new QueryWrapper<OrderMonthSale>();
            orderMonthSaleQueryWrapper.eq("month", now.minusMonths(i + 1).withDayOfMonth(1));
            orderMonthSaleQueryWrapper.eq("tenant_id",deptId);
            OrderMonthSale monthSale = this.getOne(orderMonthSaleQueryWrapper);
            if (monthSale == null) {
                monthSale = new OrderMonthSale();
                monthSale.setMonth(now.minusMonths(i + 1).withDayOfMonth(1));
                monthSale.setTenantId(deptId);
            }
            //查询每日数据
            QueryWrapper<OrderDailySale> dailyWrapper = new QueryWrapper<>();
            dailyWrapper.between("date", now.minusMonths(i + 1).withDayOfMonth(1), now.minusMonths(i).withDayOfMonth(1).minusDays(1));
            dailyWrapper.eq("tenant_id",deptId);
            List<OrderDailySale> dailySales = dailySaleService.list(dailyWrapper);
            long orderSum = 0;
            float saleSum = 0;
            for (OrderDailySale sale : dailySales) {
                orderSum += sale.getOrderNum();
                saleSum += sale.getSaleAmount();
            }
            monthSale.setOrderNum(orderSum);
            monthSale.setSaleAmount(saleSum);
            this.saveOrUpdate(monthSale);

        }
    }

}
